package com.dftdla.dao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dftdla.dao.pojo.ChatUser;
import com.dftdla.dao.pojo.UserHandler;
import com.dftdla.dao.service.ChatUserService;
import com.dftdla.dao.mapper.ChatUserMapper;
import com.dftdla.dao.service.UserHandlerService;
import com.dftdla.jwt.utils.JwtUtil;
import com.dftdla.server.session.Session;
import com.dftdla.utils.RedisKey;
import com.dftdlaRedis.cache.RedisCache;
import io.jsonwebtoken.Claims;
import io.netty.channel.Channel;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
* @author 14501
* @description 针对表【chat_user】的数据库操作Service实现
* @createDate 2023-11-28 18:18:29
*/
@Service
public class ChatUserServiceImpl extends ServiceImpl<ChatUserMapper, ChatUser>
    implements ChatUserService{

    @Resource
    private ChatUserMapper chatUserMapper;
    @Resource
    private RedisCache redisCache;
    @Resource
    private UserHandlerService userHandlerService;
    @Lazy
    @Resource
    private Session session;

    @Override
    public String register(ChatUser user) {
        return save(user)?"注册成功":"注册失败";
    }

    @Override
    public boolean canLogin(Long userId) {
        //当此用户未登录且用户合法时
        return redisCache.getCacheObject(RedisKey.loginKey(userId)) == null && chatUserMapper.selectById(userId) != null;
    }

    @Override
    public String login(Long userId) {
        String token = JwtUtil.createJWT(userId + "");
        redisCache.setCacheObject(RedisKey.loginKey(userId),token,12, TimeUnit.HOURS);

        //登录记录
        UserHandler userHandler = new UserHandler();
        userHandler.setUserId(userId);
        userHandler.setType(UserHandler.LOGIN);
        userHandlerService.save(userHandler);

        return token;
    }

    @Override
    public void logout(Long userId) {
        redisCache.deleteObject(RedisKey.loginKey(userId));

        UserHandler userHandler = new UserHandler();
        userHandler.setUserId(userId);
        userHandler.setType(UserHandler.LOGOUT);
        userHandlerService.save(userHandler);
    }

    @Override
    public boolean doAuth(String token, Channel channel) {
        boolean res;
        Claims claims;

        try {
            claims = JwtUtil.parseJWT(token);
        }catch (Exception e) {
            e.printStackTrace();
            claims = null;
        }

        if(claims == null){
            //鉴权失败
            res = false;
        }else{
            //token合法，检查是否是最新的token
            Long userId = Long.valueOf(claims.getSubject());
            Object object = redisCache.getCacheObject(RedisKey.loginKey(userId));
            res = (object != null && object.equals(token)) && (session.getUserId(channel).equals(userId));
        }
        return res;
    }
}




